#!/bin/bash

# 获取最新版
# Url=$(curl -Ls https://github.com/prometheus/node_exporter/releases |awk -F'[ "]+' '/download.*node_exporter-.*.linux-amd64.tar.gz/{print "https://github.com"$4 }' |head -n 1)
# curl -Lso /tmp/node_exporter.tar.gz $Url

# 下载软件
VERSION=0.18.1
curl -SLO http://dl.hc-yun.com/soft/monitor/node_exporter-${VERSION}.linux-amd64.tar.gz

# 解压配置
INSTALL_DIR=/usr/local/node_exporter
[ -d "$INSTALL_DIR" ] && mv $INSTALL_DIR ${INSTALL_DIR}-$(date +%s)
tar xf node_exporter-${VERSION}.linux-amd64.tar.gz
mv node_exporter-${VERSION}.linux-amd64 $INSTALL_DIR

# 创建服务
cat > /usr/lib/systemd/system/node_exporter.service <<EOF
[Unit]
Description=node_exporter server daemon
After=network.target

[Service]
Restart=on-failure
ExecStart=${INSTALL_DIR}/node_exporter --collector.systemd --collector.systemd.unit-whitelist=(docker|sshd).service
ExecReload=/bin/kill -HUP \$MAINPID

[Install]
WantedBy=multi-user.target
EOF

# 防火墙
firewall-cmd --add-port=9100/tcp --permanent
firewall-cmd --reload

# 启动服务跟随系统启动
systemctl daemon-reload
systemctl enable node_exporter
systemctl restart node_exporter
systemctl status node_exporter

echo "node_exporter dashboard:"
echo "  https://grafana.com/grafana/dashboards/9276"
echo "  https://grafana.com/grafana/dashboards/8919"
echo
echo "metrics:  http://$(hostname -I | awk '{print $1}'):9100/metrics"